﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using TruckingApplication.Dal.EntityModels;
using TruckingApplication.Web.Models;
using TruckingApplication.Common;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.IO;

namespace TruckingApplication.Web.Controllers
{
    public class AccountController : Controller
    {
        private TRUCKING_FRAMEWORK_Entities_2 entities = new TRUCKING_FRAMEWORK_Entities_2();

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    
                    // Find the User
                    var userEmail = Membership.GetUser(model.UserName).Email;
                    Dal.Infrastructure.UserSpecifics.Email = userEmail;

                    var resource = entities.RESOURCEs.Where(r => r.email == userEmail).SingleOrDefault();
                    Dal.Infrastructure.UserSpecifics.ResourceID = resource.resourceID;
                    Dal.Infrastructure.UserSpecifics.UserRole = entities.RESOURCE_TYPE.Where(r => r.resourceTypeID == resource.resourceTypeID).SingleOrDefault().resourceType;
                    Dal.Infrastructure.UserSpecifics.CompanyID = entities.RESOURCE_COMPANY.Where(rc => rc.resourceID == resource.resourceID).SingleOrDefault().companyID;
                    // Get and set user Alert count.
                    Dal.Infrastructure.UserSpecifics.AlertCount =
                        entities.ALERTs.Where(a => a.resourceId == Dal.Infrastructure.UserSpecifics.ResourceID).Where(
                            a => a.read == false).Count();

                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        //return RedirectToAction("Index", "Home");

                        var naviInfo = entities.TEMPLATEs.Where(t => t.companyId == Dal.Infrastructure.UserSpecifics.CompanyID).SingleOrDefault();
                        
                        Response.Cookies.Add(new HttpCookie("NavColor", naviInfo.templateNavColor));
                        Response.Cookies.Add(new HttpCookie("AccentColor", naviInfo.templateAccentColor));
                        Response.Cookies.Add(new HttpCookie("Logo", naviInfo.templateLogoPath));

                        return RedirectToAction("Dashboard", "Account");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Subscribe
        public ActionResult Subscribe(string type, int typeID)
        {
            ViewBag.SubscriptionType = type;
            
            ViewBag.CompanyTypeID = typeID;

            // Get the "Administrator" RESOURCE_TYPE's ID
            ViewBag.ResourceTypeID =
                entities.RESOURCE_TYPE.Where(r => r.resourceType == "ADMINISTRATOR").SingleOrDefault().resourceTypeID;

            var _s = from s in entities.STATEs select s;
            var stateList = new List<string>();
            foreach (var s in _s)
            {
                stateList.Add(s.sateAbv);
            }

            var states = new SelectList(stateList);
            //var states = new SelectList(utils.GetUSStates());
            ViewBag.States = states;
            ViewBag.CompanyStates = states;
            return View();
        }

        //
        // POST: /Account/Subscribe
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Subscribe(RegisterModel model, FormCollection collection)
        {
            //if (DateTime.Now == DateTime.Now.AddDays(7))
            {
                var companyTypeID = int.Parse(collection["CompanyTypeID"]);

                if (ModelState.IsValid)
                {
                    // Attempt to register the user
                    MembershipCreateStatus createStatus;
                    Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null,
                                          out createStatus);

                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        // Add user to Administrator Role
                        Roles.AddUserToRole(model.UserName, "Administrator");

                        Dal.Infrastructure.UserSpecifics.Email = model.Email;
                        Dal.Infrastructure.UserSpecifics.UserRole = "ADMINISTRATOR";

                        RESOURCE resource = new RESOURCE
                                                {
                                                    firstName = collection["firstName"],
                                                    lastName = collection["lastName"],
                                                    address = collection["address"],
                                                    city = collection["city"],
                                                    state = collection["States"],
                                                    zip = int.Parse(collection["zip"]),
                                                    phone = collection["phone"],
                                                    email = model.Email,
                                                    resourceTypeID = entities.RESOURCE_TYPE.Where(r => r.resourceType.ToUpper() == "ADMINISTRATOR").SingleOrDefault().resourceTypeID
                                                };
                        //entities.RESOURCEs.AddObject(resource);
                        resource.isActive = true;
                        entities.RESOURCEs.Add(resource);
                        entities.Entry(resource).State = EntityState.Added;
                        //entities.Entry(resource).State = EntityState.Added;
                        entities.SaveChanges();

                        COMPANY company = new COMPANY
                                              {
                                                  companyName = collection["companyName"],
                                                  address = collection["companyAddress"],
                                                  city = collection["companyCity"],
                                                  state = collection["CompanyStates"],
                                                  taxID = collection["taxID"],
                                                  phone = collection["companyPhone"],
                                                  web = (collection["web"] == "" ? "N/A" : collection["web"]),
                                                  email = model.Email,
                                                  adminResourceID = entities.RESOURCEs.Where(r => r.email == model.Email).SingleOrDefault().resourceID,
                                                  companyTypeID = companyTypeID
                                              };

                        //entities.Entry(company).State = EntityState.Added;
                        entities.COMPANies.Add(company);
                        entities.Entry(company).State = EntityState.Added;
                        entities.SaveChanges();
                        Dal.Infrastructure.UserSpecifics.CompanyID = company.companyID;

                        resource.parentCompanyId = company.companyID;
                        entities.Entry(resource).State = EntityState.Modified;
                        entities.SaveChanges();

                        RESOURCE_COMPANY resourceCompany = new RESOURCE_COMPANY();
                        resourceCompany.resourceID = company.adminResourceID;
                        var cID =
                            entities.COMPANies.Where(c => c.companyName == company.companyName).SingleOrDefault().
                                companyID;

                        resourceCompany.companyID = cID;

                        entities.RESOURCE_COMPANY.Add(resourceCompany);
                        entities.Entry(resourceCompany).State = EntityState.Added;
                        entities.SaveChanges();

                        FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);

                        TEMPLATE newTemplate = new TEMPLATE();
                        newTemplate.templateDescription = collection["txt_SiteBrandingName"];
                        newTemplate.templateNavColor = collection["txt_NavColor"];
                        newTemplate.templateAccentColor = collection["txt_SiteColor"];
                        
                        foreach (string file in Request.Files)
                        {
                            var uploadedFile = Request.Files[file];
                            uploadedFile.SaveAs(Server.MapPath("~/Assets/userLogo/") + Path.GetFileName(uploadedFile.FileName));
                            newTemplate.templateLogoPath = uploadedFile.FileName;// collection["fu_logo"];
                        }

                        newTemplate.companyId = resourceCompany.companyID;
                        entities.TEMPLATEs.Add(newTemplate);
                        entities.Entry(newTemplate).State = EntityState.Added;

                        try
                        {
                            entities.SaveChanges();
                        }
                        catch (DbEntityValidationException dbEx)
                        {
                            foreach (var validationErrors in dbEx.EntityValidationErrors)
                            {
                                foreach (var validationError in validationErrors.ValidationErrors)
                                {
                                    Trace.TraceInformation("Class: {0}, Property: {1}, Error: {2}",
                                        validationErrors.Entry.Entity.GetType().FullName,
                                        validationError.PropertyName,
                                        validationError.ErrorMessage);
                                }
                            }

                            throw;  // You can also choose to handle the exception here...
                        }

                        Response.Cookies.Add(new HttpCookie("NavColor", newTemplate.templateNavColor));
                        Response.Cookies.Add(new HttpCookie("AccentColor", newTemplate.templateAccentColor));
                        Response.Cookies.Add(new HttpCookie("Logo", newTemplate.templateLogoPath));

                        return RedirectToAction("Dashboard", "Account");
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(createStatus));
                    }
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult Dashboard()
        {
            return View();
        }

        //
        // GET: /Account/Register

        public ActionResult Register(string type, int typeID)
        {
            ViewBag.SubscriptionType = type;
            
            // Get the "Administrator" RESOURCE_TYPE
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        //
        // GET: /Account/Alerts

        public ActionResult Alerts()
        {
            return View(entities.ALERTs.Where(a => a.resourceId == Dal.Infrastructure.UserSpecifics.ResourceID));
        }

        public string  MarkEmailRead(string Id)
        {
            var emailId = int.Parse(Id);
            var alert = entities.ALERTs.Where(a => a.alert_Id == emailId).SingleOrDefault();
            alert.read = true;

            entities.Entry(alert).State = EntityState.Modified;
            entities.SaveChanges();
            UpdateAlertCount();
            return "ok";
        }

        private void UpdateAlertCount()
        {
            Dal.Infrastructure.UserSpecifics.AlertCount =
                                        entities.ALERTs.Where(a => a.resourceId == Dal.Infrastructure.UserSpecifics.ResourceID).Where(
                                        a => a.read == false).Count();
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        #region DASHBOARD ACTIONS

        public PartialViewResult MyOrders()
        {
            // Find the User
            var resource = entities.RESOURCEs.Where(r => r.email == Dal.Infrastructure.UserSpecifics.Email).SingleOrDefault();
            Dal.Infrastructure.UserSpecifics.ResourceID = resource.resourceID;

            // Get a list of resource types
            var resourceTypes = from e in entities.RESOURCE_TYPE select e;

            var orders = entities.ORDERs.Include("ORDER_STATUS").Where(o => o.active == true);
            List<ORDER> relevantOrders = new List<ORDER>();
            var _resource = entities.RESOURCE_COMPANY.Where(r => r.resourceID == resource.resourceID);
            long cId = _resource.First().companyID;
            Dal.Infrastructure.UserSpecifics.CompanyID = cId;
                
            if (resource.RESOURCE_TYPE.resourceType.ToLower() == "administrator")
            {
                //Show all orders
                foreach (var order in orders)
                {
                    if (entities.RESOURCEs.Where(r => r.resourceID == order.resourceID).Single().RESOURCE_COMPANY.Single().companyID == Dal.Infrastructure.UserSpecifics.CompanyID)
                        relevantOrders.Add(order);
                }
            }

            if (resource.RESOURCE_TYPE.resourceType.ToLower() == "dispatcher")
            {
                //Show my orders
                foreach (var order in orders)
                {
                    if (entities.RESOURCEs.Where(r => r.resourceID == order.dispatcherID).Single().resourceID == resource.resourceID)
                        relevantOrders.Add(order);
                }
            }

            if (resource.RESOURCE_TYPE.resourceType.ToLower() == "agent")

            {
                //Show my orders
                foreach (var order in orders)
                {
                    if (entities.RESOURCEs.Where(r => r.resourceID == order.brokerID).Single().resourceID == resource.resourceID)
                        relevantOrders.Add(order);
                }
            }

            if (resource.RESOURCE_TYPE.resourceType.ToLower() == "carrier")
            {
                //Show my orders
                foreach (var order in orders)
                {
                    if (entities.RESOURCEs.Where(r => r.resourceID == order.carrierID).Single().resourceID == resource.resourceID)
                        relevantOrders.Add(order);
                }
            }
            return PartialView(relevantOrders.ToList());
        }

        public PartialViewResult OurResources()
        {
            //var ourResources = from rc in entities.RESOURCE_COMPANY
            //                   join r in entities.RESOURCEs on rc.resourceID equals r.resourceID
            //                   join rt in entities.RESOURCE_TYPE on r.resourceTypeID equals rt.resourceTypeID
            //                   where rc.companyID == Dal.Infrastructure.UserSpecifics.CompanyID
            //                   && r.isActive == true
            //                   select new
            //                   {
            //                       Type = rt.resourceType,
            //                       Name = r.FullName,
            //                       Phone = r.phone,
            //                       Email = r.email
            //                   };

            var resourcesForMyCompany =
                entities.RESOURCE_COMPANY.Where(
                    rc => rc.companyID == Dal.Infrastructure.UserSpecifics.CompanyID).
                    Include(r => r.RESOURCE).Include(x => x.RESOURCE.RESOURCE_TYPE).
                    Where(i => i.RESOURCE.isActive == true);

            return PartialView(resourcesForMyCompany);
        }

        public PartialViewResult Payments()
        {
            return PartialView(entities.PAYMENTs.Where(p => p.companyId == Dal.Infrastructure.UserSpecifics.CompanyID));
        }

        public ActionResult Preferences()
        {
            return View();
        }

        #endregion
    }
}
